package com.code.origin.utils.string;

import cn.hutool.core.util.StrUtil;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author my
 **/
public class StringUtils extends StrUtil {
    /***/
    public static final String ERROR_INFO = "输入的文件路径不合法";
    /**逗号","*/
    public static final String REGEX_COMMA =",";
    /**下划线"_"*/
    public static final String REGEX_UNDERLINE ="_";
    /**"@"*/
    public static final String REGEX_EMAIL ="@";
    /**"*"*/
    public static final String REGEX_STAR ="*";
    /**英文中划线"-"*/
    public static final String REGEX_MIDDLE_LINE_EN ="-";

    public static boolean isPhoneNumber(String phoneNumber)
    {
        if(phoneNumber==null || "".equals(phoneNumber) || phoneNumber.length()!=11)
        {
            return false;
        }
        String regExp = "^1[1|2|3|4|5|6|7|8|9]\\d{9}$";

        Pattern p = Pattern.compile(regExp);

        Matcher m = p.matcher(phoneNumber);

        return m.find();
    }


    /**
     * 将以逗号隔开的id 转换成set,排序<Integer>
     * @param strs
     * @return
     * @throws NullPointerException
     */
    public static Set<Integer> toIntLinkedSet(String strs){
        try{
            Set<Integer> set = new LinkedHashSet<Integer>();
            for (String str : 	strs.split(REGEX_COMMA)) {
                set.add(Integer.parseInt(str.trim()));
            }
            return set;
        } catch (Exception e){
            return new HashSet<Integer>();
        }
    }


    /**
     * 将以逗号隔开的id 转换成list<Integer>
     * @param strs
     * @return
     * @throws NullPointerException
     */
    public static Set<Integer> toIntSet(String strs){
        try{
            return 	Arrays.asList(strs.split(REGEX_COMMA)).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toSet());
        } catch (Exception e){
            return new HashSet<Integer>();
        }
    }

    /**
     * 将以逗号隔开的id 转换成list<Integer>
     * @param strs
     * @return
     * @throws NullPointerException
     */
    public static List<Integer> toIntList(String strs){
        try{
            return 	Arrays.asList(strs.split(REGEX_COMMA)).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        } catch (Exception e){
            return new ArrayList<Integer>();
        }
    }

    /**
     * 将list<Integer>的id 转换成以逗号隔开的字符串
     * @param strs
     * @return
     * @throws NullPointerException
     */
    public static String intListToString(List<Integer> intList){
        StringBuffer sb = new StringBuffer();
        try{
            if (intList != null && intList.size() > 0) {
                for (int i = 0; i < intList.size(); i++) {
                    sb.append(String.valueOf(intList.get(i)));
                    if (i != (intList.size() - 1)) {
                        sb.append(REGEX_COMMA);
                    }
                }
            }

            return String.valueOf(sb);
        } catch (Exception e){
            e.printStackTrace();
            return String.valueOf(sb);
        }
    }

    /**
     * 将以逗号隔开的id 转换成list<String>
     * @param strs
     * @return
     * @throws NullPointerException
     */
    public static List<String> toStringList(String strs){
        try{
            return 	Arrays.asList(strs.split(REGEX_COMMA));
        } catch (Exception e){
            return new ArrayList<String>();
        }
    }

    /**
     * 对字符串进行由小到大排序
     * @param str    String[] 需要排序的字符串数组
     */
    public static void strSort(String[] str){
        for (int i = 0; i < str.length; i++) {
            for (int j = i+1; j < str.length; j++) {
                if(str[i].compareTo(str[j])>0){    //对象排序用camparTo方法
                    swap(str,i,j);
                }
            }
        }

    }
    /**
     * 交换两个元素的位置的方法
     * @param strSort    需要交换元素的数组
     * @param i 索引i
     * @param j 索引j
     */
    private static void swap(String[] strSort, int i, int j) {
        String t = strSort[i];
        strSort[i] = strSort[j];
        strSort[j] = t;
    }
    /**
     * 截取文件路径中文件名，不带后缀名
     * 例如：
     * 输入：    f://dota/tk.txt
     * 返回：    tk
     * @param filePath
     * @return
     */
    public static String subFileName(String filePath)
    {
        if(null == filePath || "".equals(filePath) || !filePath.contains("."))
        {
            return ERROR_INFO;
        }

        String slash = filePath.contains("\\") ? "\\" : "/";

        if(filePath.contains(slash))
        {
            int slashIndex = filePath.lastIndexOf(slash);
            filePath = filePath.substring(slashIndex + 1, filePath.length());
        }

        int pointIndex = filePath.lastIndexOf(".");
        filePath = filePath.substring(0, pointIndex);

        return filePath;
    }

    /**
     * 截取文件路径后缀名，不返回点
     * 例如：
     * 输入：    f://dota/tk.txt
     * 返回：    txt
     * @param filePath
     * @return
     */
    public static String subFileExt(String filePath)
    {
        if(null == filePath || "".equals(filePath) || !filePath.contains("."))
        {
            return ERROR_INFO;
        }

        int index = filePath.lastIndexOf(".");

        return filePath.substring(index + 1);
    }

    /**
     * 返回字符串中英文字符的个数
     * @param str
     * @return
     */
    public static int calCharNum(String str)
    {
        return (str.length() * 3 - str.getBytes().length) / 2;
    }


    /**
     * 返回字符串中大写字母的个数
     * @param str
     * @return
     */
    public static int calUpperCaseNum(String str)
    {
        char[] chars = str.toCharArray();
        int charNum = 0;
        for (char c : chars)
        {
            if(Character.isUpperCase(c))
            {
                charNum++;
            }
        }
        return charNum;
    }

    /**
     * 获取字符串的16进制值
     * @param str
     * @return
     */
    public static String getHexcode(String str)
    {
        char[] chars = str.toCharArray();
        StringBuilder builder = new StringBuilder();
        for (char c : chars)
        {
            builder.append(Integer.toHexString(c));
        }
        return builder.toString();
    }

    /**
     * 替换字符
     * @param srcStr
     * @param replacement
     * @param regexs
     * @return
     */
    public static String replaceAll(String srcStr, String replacement, String... regexs)
    {
        for (String regex : regexs)
        {
            srcStr = srcStr.replaceAll(regex, replacement);
        }
        return srcStr;
    }

    public static String replaceToApiName(String oldName, String version)
    {
        String[] apiNames=oldName.split("\\.");
        int index=apiNames.length;
        String newName=apiNames[index-1];

        return oldName.replaceAll("\\."+newName, "/"+version+"/"+newName);
    }

    /**
     * 将字符串转化为gb2312编码的字符串
     * @param str
     * @return
     */
    public static String getGbStr(String str)
    {
        try {
            return new String(str.getBytes(), "gb2312");
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        return str;
    }

    public static int calVirtualChineseNum(String mixedStr)
    {
        int charNum = calCharNum(mixedStr);
        int upperCaseNum = calUpperCaseNum(mixedStr);

        //两个英文半角小写字符相当于一个汉字, 三个大写字符相当于两个汉字
        double chineseNumOfChar = Double.valueOf((charNum - upperCaseNum) + ".0") * 0.5;
        double chineseNumOfUpperCase = Double.valueOf(upperCaseNum + ".0") / 3 * 2;

        int virtualChineseNum = (int) Math.round(chineseNumOfChar + chineseNumOfUpperCase);
        int actualChineseNum = mixedStr.length() - charNum;

        return virtualChineseNum + actualChineseNum;
    }


    /**
     * 在chars内每个字符用dilimer隔开
     * @param chars
     * @param dilimer
     * @return
     */
    public static String seperateCharsWith(String chars, String dilimer)
    {
        StringBuilder str = new StringBuilder();
        if(chars != null)
        {
            for (char c : chars.toCharArray())
            {
                str.append(c).append(dilimer);
            }
        }
        return str.lastIndexOf(dilimer) > 0 ? str.substring(0, str.length() - dilimer.length()) : str.toString();
    }

    /**
     * 判断字符串是否为空，以下范围内均属于空，包含：null,"","null","[null]"
     * @param string
     * @return 空返回true，非空false
     */
    public static boolean isEmpty(String string) {
        if (string == null || "".equals(string) || "null".equals(string) || "[null]".equals(string)) {
            return true;
        }

        return false;
    }
    
    /**
     * 判断字符串是否为空，以下范围内均属于空，包含：null,"","null","[null]"
     * @param string
     * @return 非空返回true，空false
     */
    public static boolean isNotEmpty(String string) {
    	
    	return !isEmpty(string);
    }

    /**
     * 对字符加星号处理：除前面几位和后面几位外，其他的字符以星号代替
     *
     * @param content
     *            传入的字符串
     * @param frontNum
     *            保留前面字符的位数
     * @param endNum
     *            保留后面字符的位数
     * @return 带星号的字符串
     */

    public static String getStarString(String content, int frontNum, int endNum) {

        if (frontNum >= content.length() || frontNum < 0) {
            return content;
        }
        if (endNum >= content.length() || endNum < 0) {
            return content;
        }
        if (frontNum + endNum >= content.length()) {
            return content;
        }
        String starStr = "";
        for (int i = 0; i < (content.length() - frontNum - endNum); i++) {
            starStr = starStr + "*";
        }
        return content.substring(0, frontNum) + starStr
                + content.substring(content.length() - endNum, content.length());

    }
}
